package com.qut.graduate.busrtquery.ui;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qut.graduate.busrtquery.BRTQCache;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.BusInfoLineQuery;
import com.qut.graduate.busrtquery.bean.BusLineInfo;
import com.qut.graduate.busrtquery.bean.BusStation;
import com.qut.graduate.busrtquery.bean.Route;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.fragment.LineQueryFragment;
import com.qut.graduate.busrtquery.fragment.LocNavFragment;
import com.qut.graduate.busrtquery.fragment.StationQueryFragment;
import com.qut.graduate.busrtquery.fragment.TransferFragment;
import com.qut.graduate.busrtquery.greendao.bean.BusLine;
import com.qut.graduate.busrtquery.greendao.bean.StationInfo;
import com.qut.graduate.busrtquery.ui.common.SettingActivity;
import com.qut.graduate.busrtquery.ui.user.LoginActivity;
import com.qut.graduate.busrtquery.ui.user.UserCenterActivity;
import com.qut.graduate.busrtquery.utils.common.FormatUtils;
import com.qut.graduate.busrtquery.utils.common.GsonUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.net.NetworkUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;
import com.qut.graduate.busrtquery.view.MyDialogSureCancel;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.bmob.v3.BmobUser;
import top.wefor.circularanim.CircularAnim;

/**
 * 首页，可以切换到登录、用户中心、设置界面
 * 包含定位导航、路线查询、站点查询、换乘查询四个fragment页面
 *
 * @Author WLL
 * @Time: 2019/3/18 10:16
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,
        NavigationView.OnNavigationItemSelectedListener {
    private static final String TAG = "MainActivity";
    private ArrayList<Fragment> mFragmentList = new ArrayList<>();
    //    private SPUtils mSPUtils;
    private MyHandler myHandler;
    // 搜索模块，也可去掉地图模块独立使用
    private RoutePlanSearch mSearch = null;
    private String currentCity = "";
    private BDLocation bdLocation;
    private LatLng mCurrentLatLng; // 当前经纬度
    private double mLatitude; // 当前纬度
    private double mLongitude; // 当前经度
    private DrawerLayout mDrawerLayout;
    private NavigationView mNavigationView;
    private RoundedImageView mNavigationHeaderIv;
    private TextView mNavigationHeaderTv;
    private View mNavigationHeaderLayout;
    private ImageView mBottomLocNavImage;
    private ImageView mBottomLineQueryImage;
    private ImageView mBottomStationQueryImage;
    private ImageView mBottomTransferQueryImage;
    private TextView mBottomLocNavText;
    private TextView mBottomLineQueryText;
    private TextView mBottomStationQueryText;
    private TextView mBottomTransferQueryText;

    @Override
    public void onLocationChange(BDLocation bdLocation) {
        this.bdLocation = bdLocation;
        mLatitude = bdLocation.getLatitude();
        mLongitude = bdLocation.getLongitude();
        mCurrentLatLng = new LatLng(mLatitude, mLongitude);
        currentCity = bdLocation.getCity();
        ((LocNavFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_LOC_NAV)).setBdLocation(bdLocation);
    }

    public LatLng getmCurrentLatLng() {
        return mCurrentLatLng;
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        super.onGetReverseGeoCodeResult(reverseGeoCodeResult);
        ((LocNavFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_LOC_NAV)).setNavAddressInfo(reverseGeoCodeResult);
    }

    /**
     * 定位导航页面、换乘查询界面调用此方法进行公交路径查询，查询到公交规划结果后会调用onGetTransitRouteResult
     *
     * @param currentLatLng
     * @param aimLatLng
     */
    public void searchTransitRoute(LatLng currentLatLng, LatLng aimLatLng) {
        PlanNode currentNode = PlanNode.withLocation(currentLatLng);
        PlanNode aimNode = PlanNode.withLocation(aimLatLng);
        mSearch.transitSearch((new TransitRoutePlanOption()).city(currentCity).from(currentNode).to(aimNode));
    }

    /**
     * 跳转到选择地点界面
     *
     * @param type
     */
    public void gotoSelectAddress(int type, String startPlaceName, String endPlaceName, LatLng startLatLng, LatLng endLatLng) {
        Intent intent = new Intent(MainActivity.this, SelectedPlaceActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("mAddressType", type);
        if (startLatLng != null) bundle.putParcelable("startLatLng", startLatLng);
        if (endLatLng != null) bundle.putParcelable("endLatLng", endLatLng);
        else bundle.putParcelable("endLatLng", startLatLng);
        if (startPlaceName != null) bundle.putString("startPlaceName", startPlaceName);
        else bundle.putString("startPlaceName", "");
        if (endPlaceName != null) bundle.putString("endPlaceName", endPlaceName);
        else bundle.putString("endPlaceName", "");
        LogUtils.d("----跳转到选择地点界面之前----startPlaceName: " + startPlaceName + "----endPlaceName: " + endPlaceName, getClass());
        intent.putExtras(bundle);
        startActivityForResult(intent, BRTQConstant.TRANSFER_GO_TO_SELECT_PLACE);
    }

    /**
     * 跳转到公交路线详情界面
     *
     * @param transitRouteLines
     * @param position
     * @param stNode
     * @param enNode
     */
    public void gotoBusRouteDetail(ArrayList<TransitRouteLine> transitRouteLines, int position, PlanNode stNode, PlanNode enNode) {
        Intent intent = new Intent(MainActivity.this, BusRouteDetailActivity.class);
        Bundle bundle = new Bundle();
        if (transitRouteLines != null && stNode != null && enNode != null) {
            bundle.putParcelableArrayList("transitRouteLines", transitRouteLines);
            bundle.putInt("position", position);
            bundle.putParcelable("stNode", stNode);
            bundle.putParcelable("enNode", enNode);
            LogUtils.d("----跳转到公交路线详情界面之前----stNode: " + stNode.getLocation() + "----enNode: " + enNode.getLocation(), getClass());
            intent.putExtras(bundle);
            startActivity(intent);
        } else
            ToastColorfulUtils.info("请重新选择公交规划路线");
    }

    /**
     * 跳转到公交路线实时信息界面
     *
     * @param route
     */
    public void gotoBusRouteRealTimeInfo(Route route, BusLineInfo busLineInfo, List<BusStation> busStationList) {
        Intent intent = new Intent(this, BusRouteRealTimeInfoActivity.class);
        Bundle bundle = new Bundle();
        if (currentCity != null && !currentCity.isEmpty()) {
//            bundle.putString("city", currentCity);
            bundle.putString("city", "青岛");
        } else bundle.putString("city", "青岛");
        if (route != null && busLineInfo != null && busStationList != null && busStationList.size() > 0) {
            bundle.putParcelable("route", route);
            bundle.putParcelable("busLineInfo", busLineInfo);
            bundle.putParcelableArrayList("busStationList", (ArrayList<? extends Parcelable>) busStationList);
            LogUtils.d("----跳转到公交路线实时信息界面之前----city: " + currentCity + "----busName: " + route.getRoutename(), getClass());
            intent.putExtras(bundle);
            startActivity(intent);
        } else
            ToastColorfulUtils.info("请重新点击公交线路");
    }

    /**
     * 跳转到站点查询成功界面
     *
     * @param stationInfo
     */
    public void gotoStationQuerySuccess(StationInfo stationInfo) {
        Intent intent = new Intent(MainActivity.this, StationQuerySuccessActivity.class);
        Bundle bundle = new Bundle();
        if (stationInfo != null) {
            bundle.putParcelable("stationInfo", stationInfo);
            intent.putExtras(bundle);
            startActivity(intent);
        } else
            ToastColorfulUtils.info("请重新点击站点");
    }

    private static class MyHandler extends Handler {

        private WeakReference<MainActivity> weakReference;

        public MyHandler(MainActivity mainActivity) {
            weakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = weakReference.get();
            switch (msg.what) {
                case BRTQConstant.HANDLER_LINE_QUERY_BUS_ROUTE_LIST:
                    List<BusInfoLineQuery> busInfoLineQueryList = (List<BusInfoLineQuery>) msg.obj;
                    if (busInfoLineQueryList != null && busInfoLineQueryList.size() > 0) {
                        ((LineQueryFragment) mainActivity.getmFragmentList().get(BRTQConstant.FRAGMENT_LINE_QUERY)).
                                setBusRouteRecyclerViewData(busInfoLineQueryList);
                    } else {
                        ((LineQueryFragment) mainActivity.getmFragmentList().get(BRTQConstant.FRAGMENT_LINE_QUERY)).
                                setBusRouteRecyclerViewData(null);
                    }
                    break;
            }
        }
    }

    @Override
    public void onHttpSuccess(String json, int tag) {
        String responseBusInfo = FormatUtils.unicodeToString(json);
        if (tag == BRTQConstant.HTTP_TAG_API_ROUTE) {
            initApiRoute(responseBusInfo);
        }
        if (tag == BRTQConstant.HTTP_TAG_LINE_QUERY) {
            LogUtils.d("----主页 HttpSuccess  LINE_QUERY JSON字符串" + responseBusInfo, getClass());
            List<BusInfoLineQuery> busInfoLineQueryList = GsonUtils.getInstance().jsonToList(responseBusInfo, BusInfoLineQuery.class);
//            LogUtils.d("----主页 HttpSuccess  LINE_QUERY 公交线路JSON字符串转成list" + busInfoLineQueryList, getClass());
            if (null == myHandler) myHandler = new MyHandler(this);
            Message message = Message.obtain();
            message.what = BRTQConstant.HANDLER_LINE_QUERY_BUS_ROUTE_LIST;
            message.obj = busInfoLineQueryList;
            myHandler.handleMessage(message);
        }
        if (tag == BRTQConstant.HTTP_TAG_BUS_LINE_INFO) {
            LogUtils.d("----主页 HttpSuccess  BUS_LINE_INFO JSON字符串" + responseBusInfo, getClass());
            Map<String, Route> mApiRoutesMap = BRTQCache.getInstance().getmApiRoutesMap();
            BusInfoLineQuery busInfoLineQuery = BRTQCache.getInstance().getBusInfoLineQuery();
            Route route = mApiRoutesMap.get(busInfoLineQuery.getName());
            BusLineInfo busLineInfo = GsonUtils.getInstance().getBusInfo(responseBusInfo, busInfoLineQuery);
            List<BusStation> busStationList = GsonUtils.getInstance().getBusStation(responseBusInfo, busInfoLineQuery);
            gotoBusRouteRealTimeInfo(route, busLineInfo, busStationList);
        }
        if (tag == BRTQConstant.HTTP_TAG_BUS_LINE_INFO_HC) {
            LogUtils.d("----主页 HttpSuccess  BUS_LINE_INFO JSON字符串" + responseBusInfo, getClass());
            Map<String, Route> mApiRoutesMap = BRTQCache.getInstance().getmApiRoutesMap();
            BusLine busLine = BRTQCache.getInstance().getBusLine();
            Route route = mApiRoutesMap.get(busLine.getName());
            BusLineInfo busLineInfo = GsonUtils.getInstance().getBusInfo(responseBusInfo, busLine);
            List<BusStation> busStationList = GsonUtils.getInstance().getBusStation(responseBusInfo, busLine);
            gotoBusRouteRealTimeInfo(route, busLineInfo, busStationList);
        }
    }

    public void initApiRoute(String responseBusInfo) {
        LogUtils.d("----主页 HttpSuccess  API_ROUTE JSON字符串" + responseBusInfo, getClass());
        List<Route> routeList = GsonUtils.getInstance().jsonToList(responseBusInfo, Route.class);
//            LogUtils.d("----HttpSuccess  API_ROUTE 公交线路JSON字符串转成list的size：" + routeList.size(), getClass());
        if (routeList != null) {
            Map<String, Route> mApiRoutesMap = new TreeMap<>();
            for (Route route : routeList) {
                if (route.getSegment() != null && !route.getSegment().equals("")) {
                    String segmentStr = route.getSegment().substring(route.getSegment().indexOf(":") + 2, route.getSegment().indexOf(",") - 1);
                    route.setSegment(segmentStr);
//                    LogUtils.d("----HttpSuccess  API_ROUTE 公交线路routeList:  , segementid:" + segmentStr, getClass());
                } else {
                    route.setSegment("");
                }
                mApiRoutesMap.put(route.getRoutename(), route);
//                LogUtils.d("----HttpSuccess  API_ROUTE 公交线路JSON字符串转成list:" + route, getClass());
            }
//            for (Map.Entry<String, Route> entry : mApiRoutesMap.entrySet()) {
//                LogUtils.d("----HttpSuccess  API_ROUTE 公交线路mApiRoutesMap:  Key = " + entry.getKey()
//                        + ", Value = " + entry.getValue(), getClass());
//            }
            BRTQCache.getInstance().setmApiRoutesMap(mApiRoutesMap);
        }
    }

    @Override
    public void onHttpFailed(String errorMsg, int tag) {
        LogUtils.d("----主页HttpFailed  errorMsg  " + errorMsg);
//        if (tag == BRTQConstant.HTTP_TAG_API_ROUTE) {
//            // 后来我手机已经无法访问这个网址，我猜测是被禁止访问了，然后改为读取本地json文件,之后发现应该是手机网络问题，之后发现应该是手机网络问题
//            String responseBusInfo = GsonUtils.getInstance().getJson("api_route.json", this);
//            initApiRoute(responseBusInfo);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BRTQConstant.TRANSFER_GO_TO_SELECT_PLACE && resultCode == BRTQConstant.SELECT_PLACE_BACK_TO_TRANSFER) {
            setLayoutSelect(mFragmentShowNow);
            if (data != null) {
                int mAddressType = data.getIntExtra("mAddressType", 1);
                String startPlaceName = data.getStringExtra("startPlaceName");
                String endPlaceName = data.getStringExtra("endPlaceName");
                if (startPlaceName != null && startPlaceName.equals(""))
                    startPlaceName = "我的位置";
                if (endPlaceName != null && endPlaceName.equals(""))
                    endPlaceName = "我的位置";
                LogUtils.d("----跳转选择地点返回换乘界面之后  ----startPlaceName: " + startPlaceName + "----endPlaceName: " + endPlaceName, getClass());
                LatLng startLatLng = data.getParcelableExtra("startLatLng");
                LatLng endLatLng = data.getParcelableExtra("endLatLng");
                ((TransferFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_TRANSFER_QUERY)).
                        setStartEndAddress(startPlaceName, endPlaceName, startLatLng, endLatLng);
                searchTransitRoute(startLatLng, endLatLng);
            }
        }
    }

    public BDLocation getBdLocation() {
        return bdLocation;
    }

    /**
     * 公交线路查询结果
     *
     * @param result
     */
    @Override
    public void onGetTransitRouteResult(final TransitRouteResult result) {
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (result.getRouteLines() != null) {
                LogUtils.d("----公交线路查询  GetTransitRoute  公交路线  SIZE：" + result.getRouteLines().size(), getClass());
                // 将查询到的公交路线传递到换乘查询界面
                ((TransferFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_TRANSFER_QUERY))
                        .setBusRoutePlan((ArrayList<TransitRouteLine>) result.getRouteLines());
            } else {
                LogUtils.d("----公交线路查询  GetTransitRoute  未查询到公交路线", getClass());
                ((TransferFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_TRANSFER_QUERY)).setBusRoutePlan(null);
            }
        } else {
            LogUtils.d("----公交线路查询  GetTransitRoute  未知错误,未查询到公交路线", getClass());
            ((TransferFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_TRANSFER_QUERY)).setBusRoutePlan(null);
        }
    }

    /**
     * poi检索检索到结果
     *
     * @param result
     */
    public void onGetPoiResult(PoiResult result) {
        StationQueryFragment stationQueryFragment = ((StationQueryFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_STATION_QUERY));
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            LogUtils.d("----主页  站点查询  onGetPoiResult  poi检索，未找到结果", getClass());
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST) {
                stationQueryFragment.setRefreshStop();
                stationQueryFragment.firstRequestSuggestRecyView(null);
                ToastColorfulUtils.info("您输入的站点不存在，请在重新输入");
            }
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST_MORE) {
                stationQueryFragment.setRefreshStop();
                ToastColorfulUtils.info("没有更多该搜索地点的检索结果了");
            }
        } else if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            List<PoiInfo> poiInfoList = new ArrayList<>();
            for (PoiInfo poiInfo : result.getAllPoi()) {
                poiInfoList.add(0, poiInfo);
                LogUtils.d("----主页  站点查询  onGetPoiResult  poi检索结果：" + poiInfo.getName()
                        + "  " + poiInfo.getAddress() + "  getType:" + poiInfo.getType(), getClass());
            }
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST) {
                stationQueryFragment.setRefreshStop();
                stationQueryFragment.firstRequestSuggestRecyView(poiInfoList);
            }
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST_MORE) {
                stationQueryFragment.setRefreshStop();
                stationQueryFragment.updateSuggestRecyView(poiInfoList);
            }
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_NEARBY) {
                stationQueryFragment.updateNearbyRecyView(poiInfoList, mCurrentLatLng);
            }
        } else {
            if (BRTQCache.getInstance().getSQPoiSearchType() == BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST_MORE)
                stationQueryFragment.setRefreshStop();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        super.init();
//        mSPUtils = SPUtils.getInstance(getApplicationContext());
        if (null == myHandler) myHandler = new MyHandler(this);
        initFragmentList();
        initView();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateNowTheme();
        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            mNavigationHeaderTv.setText(user.getUsername());
            String headerPath = preferenceUtils.getString(getString(R.string.preference_user_header_path), "");
            File headerFile = new File(headerPath);
            if (!(NetworkUtils.getNetworkType(this) == BRTQConstant.NETWORK_NONE)) {
                if (!headerPath.equals("") && headerFile.exists())
                    Glide.with(this).load(headerPath).into(mNavigationHeaderIv);
                if (user.getHeadImg() != null && user.getHeadImg().getFileUrl() != null)
                    Glide.with(this).load(user.getHeadImg().getFileUrl()).placeholder(R.mipmap.detach_male).into(mNavigationHeaderIv);
                else Glide.with(this).load(R.mipmap.detach_male).into(mNavigationHeaderIv);
            } else { // 没有网络从本地加载
                if (!headerPath.equals("") && headerFile.exists())
                    Glide.with(this).load(headerPath).into(mNavigationHeaderIv);
                 else Glide.with(this).load(R.mipmap.detach_male).into(mNavigationHeaderIv);
            }
        } else {
            mNavigationHeaderTv.setText("请登录");
            Glide.with(this).load(R.mipmap.detach_male).into(mNavigationHeaderIv);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connection != null) unbindService(connection);
        if (mSearch != null) mSearch.destroy();
    }

    private void updateNowTheme() {
        mNavigationView.setBackgroundColor(getPrimaryColor());
        // 显示退出主页之前fragment对应的底部布局
        setLayoutSelect(mFragmentShowNow);
        StatusBarUtils.fullScreen(this);
        updateBarColor();
    }

    private void initFragmentList() {
        if (mFragmentList.isEmpty()) {
            mFragmentList.add(new LocNavFragment());
            mFragmentList.add(new LineQueryFragment());
            mFragmentList.add(new StationQueryFragment());
            mFragmentList.add(new TransferFragment());
        }
        initBRTQuery(mFragmentList, R.id.main_frame_layout);
    }

    public ArrayList<Fragment> getmFragmentList() {
        return mFragmentList;
    }

    @Override
    public void showFragment(int fragmentId) {
        super.showFragment(fragmentId);
    }

    private void initEvent() {
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);

        mNavigationHeaderLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = BmobUser.getCurrentUser(User.class);
                if (user == null) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MainActivity.this, UserCenterActivity.class);
                    startActivity(intent);
                }
                overridePendingTransition(R.anim.activity_screen_zoom_in, R.anim.activity_screen_zoom_out);
            }
        });

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, null,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        mNavigationView.setNavigationItemSelectedListener(this);
//        mNavigationView.setCheckedItem(R.id.nav_location_navigation);

        //HttpUtil.getInstance().getAsyn(BRTQConstant.URL_API_ROUTE, this, BRTQConstant.HTTP_TAG_API_ROUTE);
        // 后来我手机已经无法访问这个网址，我猜测是被禁止访问了，然后改为读取本地json文件,之后发现应该是手机网络问题，之后发现应该是手机网络问题
        String responseBusInfo = GsonUtils.getInstance().getJson("api_route.json", this);
        initApiRoute(responseBusInfo);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_bottom_loc_nav_layout:
                showFragment(BRTQConstant.FRAGMENT_LOC_NAV);
                setLayoutSelect(BRTQConstant.FRAGMENT_LOC_NAV);
                break;
            case R.id.main_bottom_line_query_layout:
                showFragment(BRTQConstant.FRAGMENT_LINE_QUERY);
                setLayoutSelect(BRTQConstant.FRAGMENT_LINE_QUERY);
                break;
            case R.id.main_bottom_station_query_layout:
                showFragment(BRTQConstant.FRAGMENT_STATION_QUERY);
                setLayoutSelect(BRTQConstant.FRAGMENT_STATION_QUERY);
                break;
            case R.id.main_bottom_transfer_query_layout:
                gotoTransfer("我的位置", "", mCurrentLatLng, mCurrentLatLng);
                break;
        }
    }

    private long mExitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastColorfulUtils.info("再按一次退出");
                mExitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
            return true;
        }
        return false;
    }

    /**
     * 跳转到换乘界面，并根据起点、终点及其经纬度进行路径规划
     *
     * @param startPlaceName
     * @param endPlaceName
     * @param mCurrentLatLng
     * @param mAimLatLng
     */
    public void gotoTransfer(String startPlaceName, String endPlaceName, LatLng mCurrentLatLng, LatLng mAimLatLng) {
        try {
            if (mCurrentLatLng != null && mAimLatLng != null)
                searchTransitRoute(mCurrentLatLng, mAimLatLng);
            ((TransferFragment) getmFragmentList().get(BRTQConstant.FRAGMENT_TRANSFER_QUERY)).
                    setStartEndAddress(startPlaceName, endPlaceName, mCurrentLatLng, mAimLatLng);
            showFragment(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
            setLayoutSelect(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
        } catch (Exception e) {
            showFragment(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
            setLayoutSelect(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
            ToastColorfulUtils.info("网络异常");
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
        switch (item.getItemId()) {
            case R.id.nav_location_navigation:
                showFragment(BRTQConstant.FRAGMENT_LOC_NAV);
                setLayoutSelect(BRTQConstant.FRAGMENT_LOC_NAV);
                break;
            case R.id.nav_route:
                showFragment(BRTQConstant.FRAGMENT_LINE_QUERY);
                setLayoutSelect(BRTQConstant.FRAGMENT_LINE_QUERY);
                break;
            case R.id.nav_station:
                showFragment(BRTQConstant.FRAGMENT_STATION_QUERY);
                setLayoutSelect(BRTQConstant.FRAGMENT_STATION_QUERY);
                break;
            case R.id.nav_transfer:
                showFragment(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
                setLayoutSelect(BRTQConstant.FRAGMENT_TRANSFER_QUERY);
                break;
            case R.id.nav_collectManagement:
                judgeIsLogin();
                break;
            case R.id.nav_setting: // 跳转到设置界面
                CircularAnim.fullActivity(this, mNavigationView).go(new CircularAnim.OnAnimationEndListener() {
                    @Override
                    public void onAnimationEnd() {
                        Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                        startActivity(intent);
                    }
                });
                break;
        }
        return false;
    }

    /**
     * 判断用户是否登录
     */
    public void judgeIsLogin() {
        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            Intent intent = new Intent(MainActivity.this, UserCenterActivity.class);
            startActivity(intent);
        } else {
            final MyDialogSureCancel myDialogSureCancel = new MyDialogSureCancel(mContext);
            myDialogSureCancel.getTitleView().setBackgroundResource(R.mipmap.dialog_title_bg);
            myDialogSureCancel.getContentView().setText("您\t还\t未\t登\t录\t!");
            myDialogSureCancel.getSureView().setText("登录");
            myDialogSureCancel.setCancelable(false);
            myDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CircularAnim.fullActivity(MainActivity.this, mNavigationView).go(new CircularAnim.OnAnimationEndListener() {
                        @Override
                        public void onAnimationEnd() {
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                    });
                    myDialogSureCancel.cancel();
                }
            });
            myDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myDialogSureCancel.cancel();
                }
            });
            myDialogSureCancel.show();
        }
    }

    private void initView() {
        mDrawerLayout = findViewById(R.id.main_drawer_layout);
        mNavigationView = findViewById(R.id.main_nav_view);
        mNavigationHeaderLayout = mNavigationView.getHeaderView(0);
        mNavigationHeaderIv = mNavigationHeaderLayout.findViewById(R.id.nav_header_iv);
        mNavigationHeaderTv = mNavigationHeaderLayout.findViewById(R.id.nav_header_tv);

        LinearLayout mMainLayout = findViewById(R.id.main_layout);
        FrameLayout mFrameLayout = findViewById(R.id.main_frame_layout);
        LinearLayout mBottomLayout = findViewById(R.id.main_bottom_layout);
        mBottomLocNavImage = findViewById(R.id.main_bottom_loc_nav_image);
        mBottomLineQueryImage = findViewById(R.id.main_bottom_line_query_image);
        mBottomStationQueryImage = findViewById(R.id.main_bottom_station_query_image);
        mBottomTransferQueryImage = findViewById(R.id.main_bottom_transfer_query_image);
        mBottomLocNavText = findViewById(R.id.main_bottom_loc_nav_text);
        mBottomLineQueryText = findViewById(R.id.main_bottom_line_query_text);
        mBottomStationQueryText = findViewById(R.id.main_bottom_station_query_text);
        mBottomTransferQueryText = findViewById(R.id.main_bottom_transfer_query_text);
        LinearLayout mBottomLocNavLayout = findViewById(R.id.main_bottom_loc_nav_layout);
        LinearLayout mBottomLineQueryLyout = findViewById(R.id.main_bottom_line_query_layout);
        LinearLayout mBottomStationQueryLayout = findViewById(R.id.main_bottom_station_query_layout);
        LinearLayout mBottomTransferQueryLayout = findViewById(R.id.main_bottom_transfer_query_layout);

        mBottomLocNavLayout.setOnClickListener(this);
        mBottomLineQueryLyout.setOnClickListener(this);
        mBottomStationQueryLayout.setOnClickListener(this);
        mBottomTransferQueryLayout.setOnClickListener(this);
    }

    /**
     * 底部布局点击切换效果
     *
     * @param position
     */
    private void setLayoutSelect(int position) {
        ImageView[] imageViews = {mBottomLocNavImage, mBottomLineQueryImage,
                mBottomStationQueryImage, mBottomTransferQueryImage};
        TextView[] textViews = {mBottomLocNavText, mBottomLineQueryText,
                mBottomStationQueryText, mBottomTransferQueryText};
        Resources resource = getBaseContext().getResources();
        ColorStateList cslWhite = resource.getColorStateList(R.color.white);
        ColorStateList cslBlack = resource.getColorStateList(R.color.colorTextBlack);
        for (int i = 0; i < 4; i++) {
            if (i == position) {
                imageViews[i].setVisibility(View.GONE);
                textViews[i].setVisibility(View.VISIBLE);
                textViews[i].setTextColor(cslBlack);
            } else {
                imageViews[i].setVisibility(View.VISIBLE);
                textViews[i].setVisibility(View.GONE);
            }
        }
        if (preferenceUtils.getInt(getString(R.string.preference_text_color), 1) == R.color.white) {
            mNavigationView.setItemTextColor(cslWhite);
            mNavigationHeaderTv.setTextColor(cslWhite);
        } else {
            mNavigationView.setItemTextColor(cslBlack);
            mNavigationHeaderTv.setTextColor(cslBlack);
        }
    }

}
